import React, { useLayoutEffect, useMemo, useRef, useState } from "react";
import { ResourceList } from "../../Component/ResourceList";
import { FormattedMessage } from "react-intl";
import { LibAppView, utils } from "@/lib";
import { Button, message,  } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { ActivityMode, ActivityStatus} from "./Data";
import { useDelete } from "../../hooks/useDelete";
import { AdminRight } from "@/pages/Admin/data/AdminPageAuth";
import { useActivityReview } from "../../Layout/Review/useActivityReview";
import dayjs from "dayjs";
import FileManage from "../../Component/FileManage";

const ActivityList = LibAppView.withService()((props) => {
    const microApp = LibAppView.useMicroApp();
    const reviewApi = useActivityReview();
    const listRef = useRef<any>();
    const deleteAction = useDelete({
        data: {},
        endPoint:  "activity.submit",
        cancelEndPoint: "activity.updateStatus",
        listRef
    });
    const [ showChoseFile, setShowChoseFile ] = useState(false)
    const columns = useMemo(() => ([{
        title: "活动名称",
        dataIndex: "title",
        fixed: true,
        render: (title: string, data: any) => {
            return (<Button type="link" style={{whiteSpace: "normal",textAlign: "left"}} onClick={() => reviewApi.show(data.id)}>{title}</Button>);
        }
    }, {
        title: "审核拒绝原因",
        dataIndex: "approveMsg",
        width: 200,
    }, {
        title: "活动反馈",
        dataIndex: "activityResp",
        width: 120,
        render: (activityResp: string) => {
            return (activityResp ? <a target="_blank" href={activityResp}>下载文档</a> : <span>未上传</span>);
        }
    },{
        title: "开始时间",
        dataIndex: "startTime",
        width: 100,
        render: (time: string) => {
            return dayjs(time).format("YYYY-MM-DD");
        }
    }, {
        title: "结束时间",
        dataIndex: "endTime",
        width: 100,
        render: (time: string) => {
            return dayjs(time).format("YYYY-MM-DD");
        }
    },{
        title: "活动方式",
        dataIndex: "mode",
        width: 100,
        render: (val: number) => {
            const mVal = ActivityMode.find((item) => item.value === val);
            return <span>{mVal?.label}</span>
        }
    },{
        title: "活动状态",
        dataIndex: "status",
        width: 100,
        render: (val: number) => {
            const mVal = ActivityStatus.find((item) => item.value === val);
            return <span>{mVal?.label}</span>
        }
    },{
        title: "创建用户",
        dataIndex: "createUserName",
        width: 120
    },{
        title: <FormattedMessage id="admin.pages.operate.edit" />,
        dataIndex: "name",
        width: 140,
        render: (name: string, data: any) => {
            const nextProps = data.status != 0 && data.status !== -3 ? { disabled: true } : {};
            const cancelProps = data.status === 0 || data.status === -3 ? { disabled: true } : { };
            return (<>
                    <AdminRight authRight="editable" mode="disabled" nextProps={nextProps}>
                        <Button size="small" onClick={()=>{
                            microApp.startJourney("editDetails", {
                                state: {
                                    ...data,
                                    region: utils.toJSON(data.region)
                                }
                            });
                        }}>
                            <FormattedMessage id="admin.pages.operate.edit"/>
                        </Button>
                    </AdminRight>
                    <AdminRight authRight="editable" mode="disabled" nextProps={cancelProps}>
                        <Button size="small" onClick={() => {
                            deleteAction.cancel({
                                ...data
                            }, { status: -3 });
                        }}>
                            <FormattedMessage id="admin.pages.operate.cancel" />
                        </Button>
                    </AdminRight>
                    <AdminRight authRight="deleteable" mode="disabled" nextProps={nextProps}>
                        <Button size="small" onClick={() => {
                            deleteAction.delete({
                                ...data,
                                status: -1
                            })
                        }}><FormattedMessage id="admin.pages.operate.delete"/></Button>
                    </AdminRight>
                {
                    [1,2].includes(data.status) && <AdminRight authRight="editable" mode="disabled">
                        <Button size="small" onClick={() => {
                            listRef.current.data = data;
                            setShowChoseFile(true);
                        }}>活动反馈</Button>
                    </AdminRight>
                }
            </>);
        }
    }]), []);
    const searchFields = useMemo<Admin.IAdvancedField[]>(() => ([{
        label: "标题",
        name: "title",
        type: "Input"
    }, {
        label: "主办单位",
        name: "hostOrganization",
        type: "Input"
    }, {
        label: "活动方式",
        name: "mode",
        type: "Select",
        data: [
            { label: "全部", value: null },
            ...ActivityMode
        ]
    }]), []);
    useLayoutEffect(() => {
        microApp.registeJourney({
            name: "editDetails",
            title: "Edit category",
            stepJourney: true,
            isTempJourney: true,
            steps: [{
                isMemoryPage: true,
                page: "admin.activityEdit"
            }]
        });
    },[]);
    return (<>
        <ResourceList
            refApi={listRef}
            tableColumns={columns}
            searchFields={searchFields}
            tableWidth={800}
            listEndPoint={{
                endPoint: "activity.list",
                formatResponse: (resp: any) => {
                    const listData: any[] = resp.data || [];
                    return listData.map((item: any) => {
                        // const publishOwner = publishOwnerList.find((item2: any) => item2.value === item.publishOwner);
                        return {
                            ...item,
                            // publishOwnerName: publishOwner?.label || "未知",
                        };
                    });
                }
            }}
            Operators={() => {
                return (<AdminRight authRight="editable" mode="disabled">
                    <Button type="primary" onClick={() => {
                        microApp.startJourney("editDetails");
                    }}>
                        <PlusOutlined />
                        <span><FormattedMessage id="admin.pages.operate.add" /></span>
                    </Button>
                </AdminRight>);
            }}
        />
        {reviewApi.Provider}
        { showChoseFile && <FileManage
          filterType="pdf"
          onConfirm={(fileList) => {
            const fileId = fileList[0];
            listRef.current.showLoading();
            props.withServiceApi.send({
                endPoint: "activity.updateResponse",
                data: {
                    ...listRef.current.data,
                    activityResp: fileId
                }
            }).then(()=> {
                listRef.current.hideLoading();
                listRef.current.refreshData();
            }).catch((err) => {
                listRef.current.hideLoading();
                message.error(err.message || "更新失败");
            });
            setShowChoseFile(false);
          }}
          onCancel={() => {
            setShowChoseFile(false);
          }}
        /> }
        </>
    );
});

export default ActivityList;
